package com.ykt.controller;

import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.render.ContentType;
import com.ykt.common.ValueContants;
import com.ykt.common.constant.ValueConstants;
import com.ykt.common.utils.Colls;
import com.ykt.common.utils.StringUtil;
import com.ykt.common.utils.page.PageData;
import com.ykt.common.utils.page.PageParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class BaseController extends Controller{
    private final static Logger LOGGER = LoggerFactory.getLogger(BaseController.class);


    /** 把结果转换Json */
    public void returnJson(Object object) {
        String json = null;
        if(object == null){
            json = ""; // 返回空
        } else if(object instanceof String){
            json = (String) object;
        } else {
            json = JsonKit.toJson(object);
        }

        json = StringUtil.unescape(json); // 去除转义字符

        // 分页参数为空时移除掉不返回
        if(json.contains(ValueContants.PAGE_INFO_STRING)){
            json = StringUtil.trimAll(json, ValueContants.PAGE_INFO_STRING);
        }

        // 返回json字符串
        if(isIE()){
            super.renderText(json, ContentType.TEXT);
        }else {
            super.renderText(json, ContentType.JSON);
        }
    }

    private boolean isIE(){
        return getRequest().getHeader("USER-AGENT").toLowerCase().indexOf("msie") > 0;
    }

    /**获取分页参数包装对象*/
    protected <P> PageParam<P> toPageParam(P p){
        PageParam<P> param = new PageParam<>();

        Integer pageNo = this.getParaToInt("pageNo");
        if(pageNo == null){
            pageNo = 1;
            LOGGER.warn("参数 pageNo 值为空，默认设置 1！");
        }

        param.setP(p);
        param.setOffset(PageData.calcOffset(pageNo, ValueConstants.PAGE_SIZE));
        param.setPageSize(ValueConstants.PAGE_SIZE);

        return param;
    }

    /**
     * 取Request中的数据
     */
    public String getRequestString() {
        StringBuilder sb = new StringBuilder("");

        BufferedReader reader = null;
        try{

            reader = this.getRequest().getReader();
            String line = null;
            while((line = reader.readLine()) != null){
                sb.append(line);
            }

        }catch (Exception e) {
            LOGGER.error("读取字符流异常！", e);
        } finally {
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    LOGGER.error("关闭字符流异常！", e);
                }
            }
        }

        return sb.toString();
    }

    /**多个值的参数变为带,号的单个值*/
    public Map<String, String> toParaMap(){
        Map<String, String[]> map = this.getParaMap();
        if(map == null || map.isEmpty()){
            return null;
        }

        Map<String, String> params = new HashMap<>();

        for (Map.Entry<String, String[]> entry : map.entrySet()) {
            if(Colls.isEmpty(entry.getValue())){
                params.put(entry.getKey(), null);
                continue;
            }

            String value = "";
            for (String val : entry.getValue()) {
                if(val != null && !val.isEmpty()){
                    value = value.concat(",").concat(val);
                }
            }

            params.put(entry.getKey(), value);
        }

        return params;
    }

}
